/**
 *
 * 2007-11-1 下午08:38:08
 * @author xuhuan
 */

package edu.ccut.saturn.studio.logic.figure;

import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.Label;
import org.eclipse.draw2d.ToolbarLayout;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.swt.graphics.Image;

public class SaturnFigure extends Figure {

	private static final int NAME_LINE_LONG = 12;

	protected Label nameLabel;

	protected Label iconLabel;

	public SaturnFigure() {
		ToolbarLayout layout = new ToolbarLayout();

		layout.setStretchMinorAxis(false);
		layout.setMinorAlignment(ToolbarLayout.ALIGN_CENTER);
		layout.setSpacing(2);
		setLayoutManager(layout);

		super.add(iconLabel = new Label());
		super.add(nameLabel = new Label());
	}

	public String getName() {
		return nameLabel.getText();
	}

	public void setName(String name) {
		this.nameLabel.setText(restrictNameLong(name));
	}

	public void setIcon(Image image) {
		this.iconLabel.setIcon(image);
	}

	public Rectangle getTextBounds() {
		return this.nameLabel.getTextBounds();
	}

	/**
	 * 限制名字的长度，即到达一定长度(NAME_LINE_LONG)后，将进行换行。
	 * 
	 * @param name
	 * @return
	 */
	private String restrictNameLong(String name) {
		String result = "";
		String aa = name;
		if (aa.length() > NAME_LINE_LONG) {
			while (aa.length() > NAME_LINE_LONG) {
				result = result + aa.substring(0, NAME_LINE_LONG) + "\n";
				aa = aa.substring(NAME_LINE_LONG);
			}
			handleLeave(aa);
			result = result + handleLeave(aa);

		}
		if (result.equalsIgnoreCase("")) {
			result = name;
		}
		return result;
	}

	/**
	 * 处理剩下的字符串。
	 * 
	 * @param leavings
	 * @return
	 */
	private String handleLeave(String leavings) {
		String result = "";
		int stringLong = leavings.length();
		int startNum = NAME_LINE_LONG / 2 - stringLong / 2;
		String blank = " ";
		for (int i = 0; i < startNum; ++i) {
			result = result + blank;
		}
		result = result + leavings;
		return result;
	}
}